package net.jcip.examples.chapter1;

import net.jcip.annotations.*;

/**
 * LazyInitRace
 *
 * Race condition in lazy initialization
 *
 * @author Brian Goetz and Tim Peierls
 */

@NotThreadSafe
public class LazyInitRace {
    private ExpensiveObject instance = null;

    public ExpensiveObject getInstance() {
        if (instance == null)
            instance = new ExpensiveObject();
        return instance;
    }
}

class ExpensiveObject { }


/**
 * 针对单例模式的改进版本   增加同步机制以保证线程安全
 */
@ThreadSafe
class LazySafeInitRace{

    private volatile ExpensiveObject instance = null;

    public ExpensiveObject getInstance() {
        if (instance == null)
            synchronized (ExpensiveObject.class){
                if (instance == null){
                    instance = new ExpensiveObject();
                }
            }
        return instance;
    }

}

